package cool.taomu.toolkit.service.client.kademlia.service

import com.google.inject.Inject
import cool.taomu.toolkit.service.client.kademlia.utils.HttpUtils
import cool.taomu.toolkit.service.kademlia.entity.RequestDto
import cool.taomu.toolkit.service.kademlia.thrift.ServiceEntity
import javax.servlet.http.HttpServletRequest
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory

class ServiceClient {

	val static LOG = LoggerFactory.getLogger(ServiceClient)
	
	@Inject
	ServiceCentreService scservice

	def getRequestDto(HttpServletRequest request) {
		var dto = new RequestDto()
		dto.body = IOUtils.toString(request.inputStream, "UTF-8")
		dto.headers = HttpUtils.getHeaders(request)
		dto.method = request.method
		dto.contentType = request.contentType
		dto.params = HttpUtils.convertMap(request.parameterMap);
		return dto
	}

	def execute(RequestDto ... dtos) {
		var serviceEntitys = dtos.map [ dto |
			var serviceEntity = new ServiceEntity;
			serviceEntity.body = dto.body
			serviceEntity.headers = dto.headers
			serviceEntity.method = dto.method
			serviceEntity.contentType = dto.contentType
			serviceEntity.params = dto.params
			// serviceEntity.cookie = Arrays.asList(request.cookies);
			serviceEntity.serviceName = dto.serviceName
			return serviceEntity
		]
		var r  = scservice.finedServices(serviceEntitys)
		if(r.size >= 1){
		    if(r.get(0).present){
			 LOG.info("execute list one : {}",r.get(0).get())
			}
		}
		return r
	}

	def execute(String serviceName, RequestDto dto) {
		var serviceEntity = new ServiceEntity;
		serviceEntity.body = dto.body
		serviceEntity.headers = dto.headers
		serviceEntity.method = dto.method
		serviceEntity.contentType = dto.contentType
		serviceEntity.params = dto.params
		// serviceEntity.cookie = Arrays.asList(request.cookies);
		serviceEntity.serviceName = serviceName
		var result = scservice.finedService(serviceEntity)
		LOG.info("execute :{} ", result)
		return result;
	}
}
